<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElButton, ElColorPicker } from 'element-plus'
import { ArrowLeft, Delete, Picture, Refresh } from '@element-plus/icons-vue'

// 类型定义
interface ImageItem {
  id: string | number
  src: string
  name: string
  size?: string
}

interface SlotItem {
  x: number
  y: number
  width: number
  height: number
  image?: string | null
  // 图片变换属性
  imageScale?: number
  imageX?: number
  imageY?: number
  imageRotation?: number
}

interface TemplateItem {
  id: number
  name: string
  slots: SlotItem[]
}

const router = useRouter()
const { t, locale } = useI18n()

// 画布设置
const canvasWidth = ref(800)
const canvasHeight = ref(600)
const backgroundColor = ref('#ffffff')
const borderWidth = ref(0)
const borderColor = ref('#000000')
const spacing = ref(0.5)

// UI状态
const isDragOver = ref(false)
const uploadedImages = ref<ImageItem[]>([])
const fileInput = ref<HTMLInputElement>()
const selectedSlotIndex = ref<number | null>(null)
const editingSlotIndex = ref<number | null>(null)

// 鼠标拖拽状态
const isDragging = ref(false)
const dragStartX = ref(0)
const dragStartY = ref(0)
const dragStartImageX = ref(0)
const dragStartImageY = ref(0)

// 优化的模板库 - 按照示例图风格，为1-9张图片提供丰富的组合模式
const allTemplates = computed(() => [
  // 1张图片 - 单图展示
  { id: 1, name: t('templateNames.single'), slots: [{ x: 0, y: 0, width: 100, height: 100 }] },

  // 2张图片 - 多种布局
  { id: 2, name: t('templateNames.leftRight'), slots: [{ x: 0, y: 0, width: 50, height: 100 }, { x: 50, y: 0, width: 50, height: 100 }] },
  { id: 3, name: t('templateNames.topBottom'), slots: [{ x: 0, y: 0, width: 100, height: 50 }, { x: 0, y: 50, width: 100, height: 50 }] },
  { id: 4, name: t('templateNames.leftBig'), slots: [{ x: 0, y: 0, width: 70, height: 100 }, { x: 70, y: 0, width: 30, height: 100 }] },
  { id: 5, name: t('templateNames.topBig'), slots: [{ x: 0, y: 0, width: 100, height: 70 }, { x: 0, y: 70, width: 100, height: 30 }] },

  // 3张图片 - 多种组合
  { id: 6, name: t('templateNames.threeColumn'), slots: [{ x: 0, y: 0, width: 33.33, height: 100 }, { x: 33.33, y: 0, width: 33.34, height: 100 }, { x: 66.67, y: 0, width: 33.33, height: 100 }] },
  { id: 7, name: t('templateNames.threeRow'), slots: [{ x: 0, y: 0, width: 100, height: 33.33 }, { x: 0, y: 33.33, width: 100, height: 33.34 }, { x: 0, y: 66.67, width: 100, height: 33.33 }] },
  { id: 8, name: t('templateNames.leftBigRightTwo'), slots: [{ x: 0, y: 0, width: 66.67, height: 100 }, { x: 66.67, y: 0, width: 33.33, height: 50 }, { x: 66.67, y: 50, width: 33.33, height: 50 }] },
  { id: 9, name: t('templateNames.topBigBottomTwo'), slots: [{ x: 0, y: 0, width: 100, height: 66.67 }, { x: 0, y: 66.67, width: 50, height: 33.33 }, { x: 50, y: 66.67, width: 50, height: 33.33 }] },
  { id: 10, name: t('templateNames.threeMosaic'), slots: [{ x: 0, y: 0, width: 50, height: 50 }, { x: 50, y: 0, width: 50, height: 50 }, { x: 25, y: 50, width: 50, height: 50 }] },

  // 4张图片 - 多种网格
  { id: 11, name: t('templateNames.fourGrid'), slots: [{ x: 0, y: 0, width: 50, height: 50 }, { x: 50, y: 0, width: 50, height: 50 }, { x: 0, y: 50, width: 50, height: 50 }, { x: 50, y: 50, width: 50, height: 50 }] },
  { id: 12, name: t('templateNames.fourColumn'), slots: [{ x: 0, y: 0, width: 25, height: 100 }, { x: 25, y: 0, width: 25, height: 100 }, { x: 50, y: 0, width: 25, height: 100 }, { x: 75, y: 0, width: 25, height: 100 }] },
  { id: 13, name: t('templateNames.fourRow'), slots: [{ x: 0, y: 0, width: 100, height: 25 }, { x: 0, y: 25, width: 100, height: 25 }, { x: 0, y: 50, width: 100, height: 25 }, { x: 0, y: 75, width: 100, height: 25 }] },
  { id: 14, name: t('templateNames.leftOneRightThree'), slots: [{ x: 0, y: 0, width: 50, height: 100 }, { x: 50, y: 0, width: 50, height: 33.33 }, { x: 50, y: 33.33, width: 50, height: 33.34 }, { x: 50, y: 66.67, width: 50, height: 33.33 }] },
  { id: 15, name: t('templateNames.fourMix'), slots: [{ x: 0, y: 0, width: 60, height: 60 }, { x: 60, y: 0, width: 40, height: 30 }, { x: 60, y: 30, width: 40, height: 30 }, { x: 0, y: 60, width: 100, height: 40 }] },

  // 5张图片 - 创意组合
  { id: 16, name: t('templateNames.fiveColumn'), slots: [{ x: 0, y: 0, width: 20, height: 100 }, { x: 20, y: 0, width: 20, height: 100 }, { x: 40, y: 0, width: 20, height: 100 }, { x: 60, y: 0, width: 20, height: 100 }, { x: 80, y: 0, width: 20, height: 100 }] },
  { id: 17, name: t('templateNames.fiveRow'), slots: [{ x: 0, y: 0, width: 100, height: 20 }, { x: 0, y: 20, width: 100, height: 20 }, { x: 0, y: 40, width: 100, height: 20 }, { x: 0, y: 60, width: 100, height: 20 }, { x: 0, y: 80, width: 100, height: 20 }] },
  { id: 18, name: t('templateNames.centerFour'), slots: [{ x: 25, y: 25, width: 50, height: 50 }, { x: 0, y: 0, width: 25, height: 50 }, { x: 75, y: 0, width: 25, height: 50 }, { x: 0, y: 50, width: 50, height: 50 }, { x: 50, y: 50, width: 50, height: 50 }] },
  { id: 19, name: t('templateNames.fiveMix'), slots: [{ x: 0, y: 0, width: 40, height: 60 }, { x: 40, y: 0, width: 30, height: 30 }, { x: 70, y: 0, width: 30, height: 30 }, { x: 40, y: 30, width: 60, height: 30 }, { x: 0, y: 60, width: 100, height: 40 }] },

  // 6张图片 - 多样化网格
  { id: 20, name: t('templateNames.sixGrid'), slots: [{ x: 0, y: 0, width: 33.33, height: 50 }, { x: 33.33, y: 0, width: 33.34, height: 50 }, { x: 66.67, y: 0, width: 33.33, height: 50 }, { x: 0, y: 50, width: 33.33, height: 50 }, { x: 33.33, y: 50, width: 33.34, height: 50 }, { x: 66.67, y: 50, width: 33.33, height: 50 }] },
  { id: 21, name: t('templateNames.sixColumn'), slots: [{ x: 0, y: 0, width: 16.67, height: 100 }, { x: 16.67, y: 0, width: 16.66, height: 100 }, { x: 33.33, y: 0, width: 16.67, height: 100 }, { x: 50, y: 0, width: 16.67, height: 100 }, { x: 66.67, y: 0, width: 16.66, height: 100 }, { x: 83.33, y: 0, width: 16.67, height: 100 }] },
  { id: 22, name: t('templateNames.twoThreeMix'), slots: [{ x: 0, y: 0, width: 50, height: 50 }, { x: 50, y: 0, width: 50, height: 50 }, { x: 0, y: 50, width: 25, height: 50 }, { x: 25, y: 50, width: 25, height: 50 }, { x: 50, y: 50, width: 25, height: 50 }, { x: 75, y: 50, width: 25, height: 50 }] },
  { id: 23, name: t('templateNames.sixMix'), slots: [{ x: 0, y: 0, width: 50, height: 40 }, { x: 50, y: 0, width: 25, height: 40 }, { x: 75, y: 0, width: 25, height: 40 }, { x: 0, y: 40, width: 33.33, height: 60 }, { x: 33.33, y: 40, width: 33.34, height: 60 }, { x: 66.67, y: 40, width: 33.33, height: 60 }] },

  // 7张图片 - 创意布局
  { id: 24, name: t('templateNames.sevenMix1'), slots: [{ x: 0, y: 0, width: 40, height: 40 }, { x: 40, y: 0, width: 30, height: 40 }, { x: 70, y: 0, width: 30, height: 40 }, { x: 0, y: 40, width: 25, height: 60 }, { x: 25, y: 40, width: 25, height: 60 }, { x: 50, y: 40, width: 25, height: 60 }, { x: 75, y: 40, width: 25, height: 60 }] },
  { id: 25, name: t('templateNames.sevenMix2'), slots: [{ x: 0, y: 0, width: 50, height: 50 }, { x: 50, y: 0, width: 25, height: 25 }, { x: 75, y: 0, width: 25, height: 25 }, { x: 50, y: 25, width: 25, height: 25 }, { x: 75, y: 25, width: 25, height: 25 }, { x: 0, y: 50, width: 50, height: 50 }, { x: 50, y: 50, width: 50, height: 50 }] },

  // 8张图片 - 对称网格
  { id: 26, name: t('templateNames.eightGrid'), slots: [{ x: 0, y: 0, width: 25, height: 50 }, { x: 25, y: 0, width: 25, height: 50 }, { x: 50, y: 0, width: 25, height: 50 }, { x: 75, y: 0, width: 25, height: 50 }, { x: 0, y: 50, width: 25, height: 50 }, { x: 25, y: 50, width: 25, height: 50 }, { x: 50, y: 50, width: 25, height: 50 }, { x: 75, y: 50, width: 25, height: 50 }] },
  { id: 27, name: t('templateNames.eightColumn'), slots: [{ x: 0, y: 0, width: 12.5, height: 100 }, { x: 12.5, y: 0, width: 12.5, height: 100 }, { x: 25, y: 0, width: 12.5, height: 100 }, { x: 37.5, y: 0, width: 12.5, height: 100 }, { x: 50, y: 0, width: 12.5, height: 100 }, { x: 62.5, y: 0, width: 12.5, height: 100 }, { x: 75, y: 0, width: 12.5, height: 100 }, { x: 87.5, y: 0, width: 12.5, height: 100 }] },
  { id: 28, name: t('templateNames.eightMix'), slots: [{ x: 0, y: 0, width: 50, height: 33.33 }, { x: 50, y: 0, width: 25, height: 33.33 }, { x: 75, y: 0, width: 25, height: 33.33 }, { x: 0, y: 33.33, width: 25, height: 33.34 }, { x: 25, y: 33.33, width: 25, height: 33.34 }, { x: 50, y: 33.33, width: 50, height: 33.34 }, { x: 0, y: 66.67, width: 50, height: 33.33 }, { x: 50, y: 66.67, width: 50, height: 33.33 }] },

  // 9张图片 - 经典九宫格及变化
  { id: 29, name: t('templateNames.nineGrid'), slots: [{ x: 0, y: 0, width: 33.33, height: 33.33 }, { x: 33.33, y: 0, width: 33.34, height: 33.33 }, { x: 66.67, y: 0, width: 33.33, height: 33.33 }, { x: 0, y: 33.33, width: 33.33, height: 33.34 }, { x: 33.33, y: 33.33, width: 33.34, height: 33.34 }, { x: 66.67, y: 33.33, width: 33.33, height: 33.34 }, { x: 0, y: 66.67, width: 33.33, height: 33.33 }, { x: 33.33, y: 66.67, width: 33.34, height: 33.33 }, { x: 66.67, y: 66.67, width: 33.33, height: 33.33 }] },
  { id: 30, name: t('templateNames.nineColumn'), slots: [{ x: 0, y: 0, width: 11.11, height: 100 }, { x: 11.11, y: 0, width: 11.11, height: 100 }, { x: 22.22, y: 0, width: 11.11, height: 100 }, { x: 33.33, y: 0, width: 11.11, height: 100 }, { x: 44.44, y: 0, width: 11.12, height: 100 }, { x: 55.56, y: 0, width: 11.11, height: 100 }, { x: 66.67, y: 0, width: 11.11, height: 100 }, { x: 77.78, y: 0, width: 11.11, height: 100 }, { x: 88.89, y: 0, width: 11.11, height: 100 }] },
  { id: 31, name: t('templateNames.nineMix'), slots: [{ x: 0, y: 0, width: 40, height: 40 }, { x: 40, y: 0, width: 30, height: 20 }, { x: 70, y: 0, width: 30, height: 20 }, { x: 40, y: 20, width: 30, height: 20 }, { x: 70, y: 20, width: 30, height: 20 }, { x: 0, y: 40, width: 20, height: 60 }, { x: 20, y: 40, width: 20, height: 60 }, { x: 40, y: 40, width: 30, height: 60 }, { x: 70, y: 40, width: 30, height: 60 }] }
])

// 当前选中的模板
const selectedTemplateId = ref(1)

// 使用响应式的插槽数据存储
const templateSlotData = ref(new Map())

// 图片库边角控制相关状态
const hoveredImageId = ref<string | number | null>(null)
const isDraggingCorner = ref(false)
const cornerDragType = ref<'scale' | 'horizontal' | 'vertical' | 'free'>('scale')
const dragStartPos = ref({ x: 0, y: 0 })
const dragImageId = ref<string | number | null>(null)

// 获取当前选中的模板
const currentTemplate = computed(() => {
  return allTemplates.value.find(t => t.id === selectedTemplateId.value) || allTemplates.value[0]
})

// 当前插槽数据 - 使用响应式存储，应用间距设置
const currentSlots = computed(() => {
  const template = currentTemplate.value
  if (!template) return []

  const templateId = template.id
  const storedData = templateSlotData.value.get(templateId) || {}

  return template.slots.map((slot, index) => {
    // 应用间距设置
    const spacingOffset = spacing.value / 2
    const adjustedSlot = {
      ...slot,
      x: slot.x + (slot.x > 0 ? spacingOffset : 0),
      y: slot.y + (slot.y > 0 ? spacingOffset : 0),
      width: slot.width - (slot.x > 0 || slot.x + slot.width < 100 ? spacingOffset : 0) - (slot.x + slot.width < 100 ? spacingOffset : 0),
      height: slot.height - (slot.y > 0 || slot.y + slot.height < 100 ? spacingOffset : 0) - (slot.y + slot.height < 100 ? spacingOffset : 0),
      image: storedData[index]?.image || null,
      imageScale: storedData[index]?.imageScale || 1,
      imageX: storedData[index]?.imageX || 0,
      imageY: storedData[index]?.imageY || 0,
      imageRotation: storedData[index]?.imageRotation || 0
    }

    // 确保宽度和高度不会变成负数
    adjustedSlot.width = Math.max(adjustedSlot.width, 1)
    adjustedSlot.height = Math.max(adjustedSlot.height, 1)

    return adjustedSlot
  })
})

// 更新插槽数据的辅助函数
function updateSlotData(slotIndex: number, data: any) {
  const templateId = selectedTemplateId.value
  const currentData = templateSlotData.value.get(templateId) || {}

  currentData[slotIndex] = {
    ...currentData[slotIndex],
    ...data
  }

  templateSlotData.value.set(templateId, currentData)
  // 强制触发响应式更新
  templateSlotData.value = new Map(templateSlotData.value)
}

// 计算图片的默认铺满状态
function calculateFitToFill(imageSrc: string, callback: (scale: number, x: number, y: number) => void) {
  const img = new Image()
  img.onload = () => {
    // 使用标准的插槽比例 1:1 作为基准
    const containerAspectRatio = 1
    const imageAspectRatio = img.width / img.height

    let scale: number
    if (imageAspectRatio > containerAspectRatio) {
      // 图片更宽，以高度为准进行缩放
      scale = 1.2 // 稍微放大一点以确保铺满
    } else {
      // 图片更高，以宽度为准进行缩放
      scale = 1.2
    }

    // 居中定位
    const x = 0
    const y = 0

    callback(scale, x, y)
  }
  img.src = imageSrc
}

// 方法
function goBack() {
  router.push('/')
}

function selectTemplate(template: TemplateItem) {
  // 保存当前模板的图片数据
  const currentImages = new Map()
  if (currentTemplate.value) {
    currentTemplate.value.slots.forEach((slot, index) => {
      if ((slot as any).image) {
        currentImages.set(index, {
          image: (slot as any).image,
          imageScale: (slot as any).imageScale || 1,
          imageX: (slot as any).imageX || 0,
          imageY: (slot as any).imageY || 0,
          imageRotation: (slot as any).imageRotation || 0
        })
      }
    })
  }

  selectedTemplateId.value = template.id
  
  // 尝试保留图片到新模板的对应位置
  template.slots.forEach((slot, index) => {
    if (currentImages.has(index)) {
      const imageData = currentImages.get(index)
      Object.assign(slot, imageData)
    } else {
      // 重置插槽
      (slot as any).image = null;
      (slot as any).imageScale = 1;
      (slot as any).imageX = 0;
      (slot as any).imageY = 0;
      (slot as any).imageRotation = 0
    }
  })
}

function selectSlot(index: number) {
  // 如果插槽已有图片，不触发上传
  if (currentSlots.value[index]?.image) {
    return
  }
  
}

function handleDrop(event: DragEvent, slotIndex: number) {
  event.preventDefault()
  const imageId = event.dataTransfer?.getData('text/plain')
  if (imageId) {
    const image = uploadedImages.value.find(img => String(img.id) === imageId)
    if (image) {
      // 计算铺满状态并应用
      calculateFitToFill(image.src, (scale, x, y) => {
        updateSlotData(slotIndex, {
          image: image.src,
          imageScale: scale,
          imageX: x,
          imageY: y,
          imageRotation: 0
        })
      })
    }
  }
}

function handleImageDragStart(event: DragEvent, image: ImageItem) {
  if (event.dataTransfer) {
    event.dataTransfer.setData('text/plain', String(image.id))
    event.dataTransfer.effectAllowed = 'copy'
  }
}

function handleFileSelect(event: Event) {
  const files = (event.target as HTMLInputElement).files
  if (files) {
    Array.from(files).forEach(file => {
      if (file.type.startsWith('image/')) {
        const reader = new FileReader()
        reader.onload = (e) => {
          if (e.target?.result) {
            const newImage: ImageItem = {
              id: Date.now() + Math.random(),
              src: e.target.result as string,
              name: file.name,
              size: `${Math.round(file.size / 1024)}KB`
            }
            uploadedImages.value.push(newImage)

            // 如果有选中的插槽，自动填充
            if (selectedSlotIndex.value !== null) {
              const slotIndex = selectedSlotIndex.value
              // 计算铺满状态并应用
              calculateFitToFill(newImage.src, (scale, x, y) => {
                updateSlotData(slotIndex, {
                  image: newImage.src,
                  imageScale: scale,
                  imageX: x,
                  imageY: y,
                  imageRotation: 0
                })
              })
              selectedSlotIndex.value = null
            }
          }
        }
        reader.readAsDataURL(file)
      }
    })
  }
  // 重置文件输入
  if (event.target) {
    (event.target as HTMLInputElement).value = ''
  }
}

function handleImageDrop(event: DragEvent) {
  event.preventDefault()
  isDragOver.value = false
  const files = event.dataTransfer?.files
  if (files) {
    Array.from(files).forEach(file => {
      if (file.type.startsWith('image/')) {
        const reader = new FileReader()
        reader.onload = (e) => {
          if (e.target?.result) {
            const newImage: ImageItem = {
              id: Date.now() + Math.random(),
              src: e.target.result as string,
              name: file.name,
              size: `${Math.round(file.size / 1024)}KB`
            }
            uploadedImages.value.push(newImage)
          }
        }
        reader.readAsDataURL(file)
      }
    })
  }
}

// 鼠标拖拽功能
function handleImageMouseDown(event: MouseEvent, slotIndex: number) {
  if (!currentSlots.value[slotIndex]?.image) return

  event.preventDefault()
  event.stopPropagation()
  isDragging.value = true
  editingSlotIndex.value = slotIndex
  dragStartX.value = event.clientX
  dragStartY.value = event.clientY
  dragStartImageX.value = currentSlots.value[slotIndex].imageX || 0
  dragStartImageY.value = currentSlots.value[slotIndex].imageY || 0

  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
}

function handleMouseMove(event: MouseEvent) {
  if (!isDragging.value || editingSlotIndex.value === null) return

  const deltaX = event.clientX - dragStartX.value
  const deltaY = event.clientY - dragStartY.value

  // 计算移动百分比（相对于插槽大小）
  const moveX = (deltaX / 3) // 调整灵敏度
  const moveY = (deltaY / 3)

  const newX = Math.max(-200, Math.min(200, dragStartImageX.value + moveX))
  const newY = Math.max(-200, Math.min(200, dragStartImageY.value + moveY))

  // 使用新的响应式更新方法
  updateSlotData(editingSlotIndex.value, {
    imageX: newX,
    imageY: newY
  })
}

function handleMouseUp() {
  isDragging.value = false
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)
}

// 鼠标滚轮缩放
function handleWheel(event: WheelEvent, slotIndex: number) {
  if (!currentSlots.value[slotIndex]?.image) return

  event.preventDefault()
  event.stopPropagation()
  editingSlotIndex.value = slotIndex

  // 进一步降低滚轮灵敏度，从0.02改为0.01，使缩放更加精细
  const delta = event.deltaY > 0 ? -0.02 : 0.02
  const currentScale = currentSlots.value[slotIndex].imageScale || 1
  const newScale = Math.max(0.1, Math.min(5, currentScale + delta))

  // 使用新的响应式更新方法
  updateSlotData(slotIndex, {
    imageScale: newScale
  })
}

// 删除图片
function removeImage(imageId: string | number) {
  const imageToRemove = uploadedImages.value.find(img => img.id === imageId)
  if (!imageToRemove) return
  
  const index = uploadedImages.value.findIndex(img => img.id === imageId)
  if (index > -1) {
    uploadedImages.value.splice(index, 1)
  }
  
  // 同时从插槽中移除该图片
  if (currentTemplate.value) {
    currentTemplate.value.slots.forEach(slot => {
      if ((slot as any).image === imageToRemove.src) {
        (slot as any).image = null;
        (slot as any).imageScale = 1;
        (slot as any).imageX = 0;
        (slot as any).imageY = 0;
        (slot as any).imageRotation = 0
      }
    })
  }
}

// 清空插槽
function clearSlot(slotIndex: number) {
  updateSlotData(slotIndex, {
    image: null,
    imageScale: 1,
    imageX: 0,
    imageY: 0,
    imageRotation: 0
  })
}

// 重置图片变换
function resetImageTransform(slotIndex: number) {
  updateSlotData(slotIndex, {
    imageScale: 1,
    imageX: 0,
    imageY: 0,
    imageRotation: 0
  })
}

// 精准移动图片
function moveImage(slotIndex: number, deltaX: number, deltaY: number) {
  const currentSlot = currentSlots.value[slotIndex]
  if (currentSlot && currentSlot.image) {
    const newX = (currentSlot.imageX || 0) + deltaX
    const newY = (currentSlot.imageY || 0) + deltaY

    updateSlotData(slotIndex, {
      imageX: Math.max(-200, Math.min(200, newX)),
      imageY: Math.max(-200, Math.min(200, newY))
    })
  }
}

// 精准缩放图片
function scaleImage(slotIndex: number, deltaScale: number) {
  const currentSlot = currentSlots.value[slotIndex]
  if (currentSlot && currentSlot.image) {
    const newScale = (currentSlot.imageScale || 1) + deltaScale

    updateSlotData(slotIndex, {
      imageScale: Math.max(0.1, Math.min(5, newScale))
    })
  }
}

// 键盘事件处理
function handleKeyDown(event: KeyboardEvent) {
  if (editingSlotIndex.value === null) return

  const slotIndex = editingSlotIndex.value
  const step = event.shiftKey ? 10 : 2 // Shift键加速移动

  switch (event.key) {
    case 'ArrowUp':
      event.preventDefault()
      moveImage(slotIndex, 0, -step)
      break
    case 'ArrowDown':
      event.preventDefault()
      moveImage(slotIndex, 0, step)
      break
    case 'ArrowLeft':
      event.preventDefault()
      moveImage(slotIndex, -step, 0)
      break
    case 'ArrowRight':
      event.preventDefault()
      moveImage(slotIndex, step, 0)
      break
    case '=':
    case '+':
      event.preventDefault()
      scaleImage(slotIndex, 0.05)
      break
    case '-':
      event.preventDefault()
      scaleImage(slotIndex, -0.05)
      break
    case 'r':
    case 'R':
      if (event.ctrlKey || event.metaKey) {
        event.preventDefault()
        resetImageTransform(slotIndex)
      }
      break
  }
}

// 自动填充所有插槽
function autoFillSlots() {
  if (uploadedImages.value.length === 0) return

  currentSlots.value.forEach((slot, index) => {
    if (uploadedImages.value[index]) {
      const image = uploadedImages.value[index]
      // 计算铺满状态并应用
      calculateFitToFill(image.src, (scale, x, y) => {
        updateSlotData(index, {
          image: image.src,
          imageScale: scale,
          imageX: x,
          imageY: y,
          imageRotation: 0
        })
      })
    }
  })
}

// 清空所有插槽
function clearAllSlots() {
  if (currentTemplate.value) {
    currentTemplate.value.slots.forEach(slot => {
      (slot as any).image = null;
      (slot as any).imageScale = 1;
      (slot as any).imageX = 0;
      (slot as any).imageY = 0;
      (slot as any).imageRotation = 0
    })
  }
}

function exportCanvas() {
  // 创建一个canvas来绘制最终图片
  const canvas = document.createElement('canvas')
  const totalWidth = canvasWidth.value + (borderWidth.value * 2)
  const totalHeight = canvasHeight.value + (borderWidth.value * 2)
  canvas.width = totalWidth
  canvas.height = totalHeight
  const ctx = canvas.getContext('2d')

  if (ctx) {
    // 绘制边框（如果有）
    if (borderWidth.value > 0) {
      ctx.fillStyle = borderColor.value
      ctx.fillRect(0, 0, totalWidth, totalHeight)
    }

    // 设置背景色
    ctx.fillStyle = backgroundColor.value
    ctx.fillRect(borderWidth.value, borderWidth.value, canvasWidth.value, canvasHeight.value)

    // 绘制每个插槽的图片
    const promises = currentSlots.value.map((slot, index) => {
      return new Promise<void>((resolve) => {
        if (slot.image) {
          const img = new Image()
          img.onload = () => {
            // 计算插槽在画布上的实际位置和大小
            const slotX = (slot.x / 100) * canvasWidth.value + borderWidth.value
            const slotY = (slot.y / 100) * canvasHeight.value + borderWidth.value
            const slotWidth = (slot.width / 100) * canvasWidth.value
            const slotHeight = (slot.height / 100) * canvasHeight.value

            // 保存画布状态
            ctx.save()

            // 设置裁剪区域为插槽区域
            ctx.beginPath()
            ctx.rect(slotX, slotY, slotWidth, slotHeight)
            ctx.clip()

            // 计算图片的原始宽高比
            const imgAspect = img.width / img.height
            const slotAspect = slotWidth / slotHeight

            // 计算图片在插槽中的基础尺寸（填充整个插槽）
            let baseWidth, baseHeight
            if (imgAspect > slotAspect) {
              // 图片更宽，以高度为准
              baseHeight = slotHeight
              baseWidth = baseHeight * imgAspect
            } else {
              // 图片更高，以宽度为准
              baseWidth = slotWidth
              baseHeight = baseWidth / imgAspect
            }

            // 应用用户的缩放
            const scale = slot.imageScale || 1
            const finalWidth = baseWidth * scale
            const finalHeight = baseHeight * scale

            // 计算图片中心位置
            const centerX = slotX + slotWidth / 2
            const centerY = slotY + slotHeight / 2

            // 应用用户的偏移（转换为像素值）
            const offsetX = (slot.imageX || 0) * slotWidth / 100
            const offsetY = (slot.imageY || 0) * slotHeight / 100

            // 计算最终绘制位置
            const drawX = centerX - finalWidth / 2 + offsetX
            const drawY = centerY - finalHeight / 2 + offsetY

            // 绘制图片
            ctx.drawImage(img, drawX, drawY, finalWidth, finalHeight)

            // 恢复画布状态
            ctx.restore()
            resolve()
          }
          img.crossOrigin = 'anonymous'
          img.src = slot.image
        } else {
          resolve()
        }
      })
    })

    Promise.all(promises).then(() => {
      const dataURL = canvas.toDataURL('image/png', 1.0)
      const link = document.createElement('a')
      link.download = `${t('templates.title') === 'Template Library' ? 'collage' : '拼图'}-${Date.now()}.png`
      link.href = dataURL
      link.click()
    })
  }
}

function saveProject() {
  const projectData = {
    templateId: selectedTemplateId.value,
    canvasWidth: canvasWidth.value,
    canvasHeight: canvasHeight.value,
    backgroundColor: backgroundColor.value,
    slots: currentSlots.value,
    uploadedImages: uploadedImages.value,
    timestamp: Date.now()
  }
  localStorage.setItem('collage-project', JSON.stringify(projectData))
  console.log(t('templates.title') === 'Template Library' ? 'Project saved!' : '项目已保存！')
}

// 响应式示例图片
const sampleImages = computed(() => {
  const lang = locale.value === 'zh' ? 'zh' : 'en'

  return [
    { id: 'sample1', src: `/test-images/${lang}/sample1.svg`, name: t('templates.title') === 'Template Library' ? 'Nature.svg' : '自然风景.svg', size: '400x400' },
    { id: 'sample2', src: `/test-images/${lang}/sample2.svg`, name: t('templates.title') === 'Template Library' ? 'Travel.svg' : '旅行冒险.svg', size: '400x400' },
    { id: 'sample3', src: `/test-images/${lang}/sample3.svg`, name: t('templates.title') === 'Template Library' ? 'Portrait.svg' : '人像摄影.svg', size: '400x400' },
    { id: 'sample4', src: `/test-images/${lang}/sample4.svg`, name: t('templates.title') === 'Template Library' ? 'Lifestyle.svg' : '生活方式.svg', size: '400x400' },
    { id: 'sample5', src: `/test-images/${lang}/sample5.svg`, name: t('templates.title') === 'Template Library' ? 'Fashion.svg' : '时尚风格.svg', size: '400x400' }
  ]
})

// 添加示例图片
function addSampleImages() {
  uploadedImages.value.push(...sampleImages.value)
}

// 监听语言变化，更新示例图片
watch(locale, () => {
  // 清除现有的示例图片
  uploadedImages.value = uploadedImages.value.filter(img => !img.id.toString().startsWith('sample'))
  // 添加新语言的示例图片
  uploadedImages.value.push(...sampleImages.value)
})

onMounted(() => {
  // 默认选择第一个模板
  selectTemplate(allTemplates.value[0])
  // 添加示例图片
  addSampleImages()
  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeyDown)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyDown)
  document.removeEventListener('mousemove', handleCornerDrag)
  document.removeEventListener('mouseup', stopCornerDrag)
})

// 边角拖拽功能
function startCornerDrag(event: MouseEvent, imageId: string | number, type: 'scale' | 'horizontal' | 'vertical' | 'free') {
  event.preventDefault()
  event.stopPropagation()

  isDraggingCorner.value = true
  cornerDragType.value = type
  dragImageId.value = imageId
  dragStartPos.value = { x: event.clientX, y: event.clientY }

  document.addEventListener('mousemove', handleCornerDrag)
  document.addEventListener('mouseup', stopCornerDrag)
}

function handleCornerDrag(event: MouseEvent) {
  if (!isDraggingCorner.value || dragImageId.value === null) return

  const deltaX = event.clientX - dragStartPos.value.x
  const deltaY = event.clientY - dragStartPos.value.y

  // 这里可以根据不同的拖拽类型实现不同的效果
  // 由于图片库中的图片主要用于预览，我们可以添加一些视觉反馈
  console.log(`拖拽类型: ${cornerDragType.value}, 移动距离: ${deltaX}, ${deltaY}`)
}

function stopCornerDrag() {
  isDraggingCorner.value = false
  dragImageId.value = null

  document.removeEventListener('mousemove', handleCornerDrag)
  document.removeEventListener('mouseup', stopCornerDrag)
}
</script>

<template>
  <div class="editor-container">
    <!-- 左侧模板面板 -->
    <div class="template-panel">
      <div class="panel-header">
        <h2>{{ t('templates.title') }}</h2>
        <span class="template-count">{{ allTemplates.length }} {{ t('templates.title') === 'Template Library' ? 'layouts' : '个布局' }}</span>
      </div>

      <!-- 模板网格 - 显示所有模板 -->
      <div class="template-grid">
        <div
          v-for="template in allTemplates"
          :key="template.id"
          @click="selectTemplate(template)"
          class="template-item"
          :class="{ 'active': selectedTemplateId === template.id }"
        >
          <div class="template-preview">
            <div
              v-for="(slot, index) in template.slots"
              :key="index"
              class="template-slot"
              :style="{
                left: `${slot.x}%`,
                top: `${slot.y}%`,
                width: `${slot.width}%`,
                height: `${slot.height}%`
              }"
            ></div>
          </div>
          <div class="template-info">
            <div class="template-count">{{ template.slots.length }} {{ t('templates.title') === 'Template Library' ? 'images' : '张图片' }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主画布区域 -->
    <div class="main-canvas">
      <!-- 顶部工具栏 -->
      <div class="top-toolbar">
        <div class="toolbar-left">
          <ElButton @click="goBack" text>
            <ArrowLeft />
            {{ t('editor.back') }}
          </ElButton>
        </div>

        <div class="toolbar-center">
          <span class="toolbar-title">{{ t('editor.title') }}</span>
          <div class="toolbar-tips">
            <span>{{ t('editor.tips') }}</span>
          </div>
        </div>

        <div class="toolbar-right">
          <ElButton @click="clearAllSlots" text size="small">{{ t('editor.clear') }}</ElButton>
          <ElButton @click="autoFillSlots" text size="small">{{ t('editor.autoFill') }}</ElButton>
          <ElButton @click="saveProject" text size="small">{{ t('editor.save') }}</ElButton>
          <ElButton @click="exportCanvas" type="primary" size="small">{{ t('editor.download') }}</ElButton>
        </div>
      </div>

      <!-- 画布容器 -->
      <div class="canvas-container">
        <div class="canvas-wrapper">
          <div
            class="canvas"
            :style="{
              width: canvasWidth + 'px',
              height: canvasHeight + 'px',
              backgroundColor: backgroundColor,
              border: borderWidth > 0 ? `${borderWidth}px solid ${borderColor}` : 'none'
            }"
          >
            <!-- 模板插槽渲染 -->
            <div
              v-for="(slot, index) in currentSlots"
              :key="index"
              class="canvas-slot"
              :class="{
                'has-image': !!slot.image,
                'editing': editingSlotIndex === index
              }"
              :style="{
                position: 'absolute',
                left: `${slot.x}%`,
                top: `${slot.y}%`,
                width: `${slot.width}%`,
                height: `${slot.height}%`,
                border: '1px solid #adb5bd',
                background: slot.image ? '#fff' : '#f0f0f0',
                overflow: 'hidden',
                cursor: slot.image ? 'grab' : 'pointer'
              }"
              @click="selectSlot(index)"
              @drop="handleDrop($event, index)"
              @dragover.prevent
              @mousedown="handleImageMouseDown($event, index)"
              @wheel="handleWheel($event, index)"
            >
              <template v-if="slot.image">
                <div class="slot-image-container" style="width:100%;height:100%;position:relative;">
                  <img
                    :src="slot.image"
                    draggable="false"
                    :style="{
                      position: 'absolute',
                      left: '50%',
                      top: '50%',
                      width: 'auto',
                      height: 'auto',
                      minWidth: '100%',
                      minHeight: '100%',
                      transform: `translate(-50%, -50%) translate(${slot.imageX || 0}%, ${slot.imageY || 0}%) scale(${slot.imageScale || 1}) rotate(${slot.imageRotation || 0}deg)`,
                      objectFit: 'cover',
                      pointerEvents: 'none',
                      userSelect: 'none',
                      transformOrigin: 'center center'
                    }"
                  />
                  <ElButton
                    class="slot-clear-btn"
                    @click.stop="clearSlot(index)"
                    circle
                    size="small"
                    style="position:absolute;top:4px;right:4px;z-index:2;background:#dc3545 !important;border:none !important;color:white !important;box-shadow:0 2px 4px rgba(0,0,0,0.2);"
                  >
                    <Delete style="color:white !important;" />
                  </ElButton>
                  <ElButton
                    class="slot-reset-btn"
                    @click.stop="resetImageTransform(index)"
                    circle
                    size="small"
                    style="position:absolute;top:4px;right:36px;z-index:2;background:#28a745 !important;border:none !important;color:white !important;box-shadow:0 2px 4px rgba(0,0,0,0.2);"
                  >
                    <Refresh style="color:white !important;" />
                  </ElButton>
                </div>
              </template>
              <template v-else>
                <div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;color:#bbb;font-size:14px;">
                  <Picture style="font-size:24px;" />
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧图片库 -->
    <div class="photo-panel">
      <div class="panel-header">
        <h3>{{ t('editor.imageLibrary') }}</h3>
      </div>

      <div class="panel-content">
        <!-- 拖拽上传区域 -->
        <div
          class="upload-zone"
          @drop="handleImageDrop"
          @dragover.prevent
          @dragenter="isDragOver = true"
          @dragleave="isDragOver = false"
          :class="{ 'drag-over': isDragOver }"
          @click="fileInput?.click()"
        >
          <div class="upload-content">
            <Picture />
            <p>{{ t('editor.dragUpload') }}</p>
            <span>{{ t('editor.supportedFormats') }}</span>
          </div>
        </div>

        <!-- 图片列表 -->
        <div v-if="uploadedImages.length > 0" class="photo-list">
          <div class="photo-header">
            <span>{{ uploadedImages.length }} {{ t('editor.dragMove').includes('images') ? 'images' : '张图片' }}</span>
            <button v-if="uploadedImages.length > 0" @click="uploadedImages = []" class="clear-btn">
              {{ t('editor.clear') }}
            </button>
          </div>

          <div class="photo-grid">
            <div
              v-for="image in uploadedImages"
              :key="image.id"
              class="photo-item"
              draggable="true"
              @dragstart="handleImageDragStart($event, image)"
              @mouseenter="hoveredImageId = image.id"
              @mouseleave="hoveredImageId = null"
            >
              <div class="photo-thumbnail">
                <img :src="image.src" :alt="image.name" />
                <div class="photo-overlay">
                  <button @click="removeImage(image.id)" class="remove-btn">
                    <Delete />
                  </button>
                </div>

                <!-- 边角控制点 -->
                <div v-if="hoveredImageId === image.id" class="corner-controls">
                  <!-- 左上角 - 等比缩放 -->
                  <div
                    class="corner-handle corner-tl"
                    @mousedown="startCornerDrag($event, image.id, 'scale')"
                    title="等比缩放"
                  ></div>
                  <!-- 右上角 - 水平拉伸 -->
                  <div
                    class="corner-handle corner-tr"
                    @mousedown="startCornerDrag($event, image.id, 'horizontal')"
                    title="水平调整"
                  ></div>
                  <!-- 左下角 - 垂直拉伸 -->
                  <div
                    class="corner-handle corner-bl"
                    @mousedown="startCornerDrag($event, image.id, 'vertical')"
                    title="垂直调整"
                  ></div>
                  <!-- 右下角 - 自由变形 -->
                  <div
                    class="corner-handle corner-br"
                    @mousedown="startCornerDrag($event, image.id, 'free')"
                    title="自由变形"
                  ></div>
                </div>
              </div>
              <div class="photo-info">
                <div class="photo-name">{{ image.name }}</div>
                <div class="photo-size">{{ image.size }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 画布设置 -->
        <div class="canvas-settings">
          <h4>{{ t('templates.title') === 'Template Library' ? 'Canvas Settings' : '画布设置' }}</h4>

          <div class="setting-group">
            <label>{{ t('templates.title') === 'Template Library' ? 'Size' : '尺寸' }}</label>
            <div class="size-inputs">
              <input v-model.number="canvasWidth" type="number" min="100" max="2000" :placeholder="t('templates.title') === 'Template Library' ? 'Width' : '宽度'" />
              <span>×</span>
              <input v-model.number="canvasHeight" type="number" min="100" max="2000" :placeholder="t('templates.title') === 'Template Library' ? 'Height' : '高度'" />
            </div>
          </div>

          <div class="setting-group">
            <label>{{ t('templates.title') === 'Template Library' ? 'Background Color' : '背景颜色' }}</label>
            <ElColorPicker v-model="backgroundColor" />
          </div>

          <div class="setting-group">
            <label>{{ t('templates.title') === 'Template Library' ? 'Border' : '边框' }}</label>
            <div class="border-inputs">
              <input v-model.number="borderWidth" type="number" min="0" max="20" :placeholder="t('templates.title') === 'Template Library' ? 'Width' : '宽度'" />
              <ElColorPicker v-model="borderColor" />
            </div>
          </div>

          <div class="setting-group">
            <label>{{ t('templates.title') === 'Template Library' ? 'Image Spacing' : '图片间距' }}</label>
            <input v-model.number="spacing" type="number" min="0" max="20" :placeholder="t('templates.title') === 'Template Library' ? 'Spacing' : '间距'" />
          </div>
        </div>
      </div>

      <!-- 隐藏的文件输入 -->
      <input
        type="file"
        multiple
        accept="image/*"
        @change="handleFileSelect"
        style="display: none"
        ref="fileInput"
      />
    </div>
  </div>
</template>

<style scoped>
/* 简洁设计系统 */
.editor-container {
  display: flex;
  height: 100vh;
  background: #f8f9fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
}

/* 左侧模板面板 */
.template-panel {
  width: 320px;
  background: white;
  border-right: 1px solid #e9ecef;
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.panel-header {
  padding: 20px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.panel-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #212529;
}

.template-count {
  font-size: 14px;
  color: #6c757d;
}

/* 模板网格 - 优化显示 */
.template-grid {
  padding: 20px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  overflow-y: auto;
  flex: 1;
  height: calc(100vh - 120px); /* 固定高度确保不超出视口 */
}

.template-item {
  border: 2px solid #e9ecef;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: white;
  overflow: visible; /* 改为可见，避免裁剪预览内容 */
  padding: 8px;
}

.template-item:hover {
  border-color: #007bff;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.15);
  transform: translateY(-1px);
}

.template-item.active {
  border-color: #007bff;
  background: #e7f3ff;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.25);
}

.template-preview {
  width: 100%;
  height: 80px; /* 增加高度确保不被裁剪 */
  position: relative;
  background: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 6px;
  border: 1px solid #dee2e6;
  padding: 6px; /* 增加内边距 */
  box-sizing: border-box;
  overflow: visible; /* 改为可见，避免裁剪 */
}

.template-preview svg {
  width: 100%;
  height: 100%;
  display: block;
}

.template-slot {
  position: absolute;
  background: white;
  border: 1px solid #adb5bd;
  border-radius: 1px;
  box-sizing: border-box;
  min-width: 4px; /* 增加最小宽度 */
  min-height: 4px; /* 增加最小高度 */
}

.template-item.active .template-slot {
  background: #cce7ff;
  border-color: #007bff;
}

.template-info {
  text-align: center;
}

.template-name {
  font-size: 12px;
  font-weight: 600;
  color: #212529;
  margin-bottom: 2px;
}

.template-item .template-count {
  font-size: 10px;
  color: #6c757d;
}

/* 主画布区域 */
.main-canvas {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
}

.top-toolbar {
  height: 80px;
  background: white;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
}

.toolbar-left, .toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.toolbar-center {
  flex: 1;
  text-align: center;
}

.toolbar-title {
  font-size: 18px;
  font-weight: 600;
  color: #212529;
  display: block;
  margin-bottom: 4px;
}

.toolbar-tips {
  font-size: 12px;
  color: #6c757d;
}

.canvas-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  overflow: auto;
}

.canvas-wrapper {
  position: relative;
}

.canvas {
  position: relative;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 画布插槽 - 优化交互体验 */
.canvas-slot {
  position: absolute;
  border: 2px dashed #dee2e6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  background: rgba(248, 249, 250, 0.8);
  overflow: hidden;
}

.canvas-slot:hover {
  border-color: #007bff;
  background: rgba(0, 123, 255, 0.05);
}

.canvas-slot.has-image {
  border: 2px solid #007bff;
  cursor: grab;
}

.canvas-slot.has-image:active {
  cursor: grabbing;
}

.canvas-slot.editing {
  border-color: #28a745;
  box-shadow: 0 0 0 2px rgba(40, 167, 69, 0.25);
}

.slot-image-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.1s ease;
  transform-origin: center;
  cursor: grab;
}

.slot-image-container:active {
  cursor: grabbing;
}

.slot-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 2px;
  user-select: none;
}

.slot-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  color: #6c757d;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
  height: 100%;
  width: 100%;
}

.slot-placeholder svg {
  font-size: 20px;
  margin-bottom: 4px;
}

.slot-number {
  font-size: 10px;
  color: #adb5bd;
  background: white;
  padding: 2px 6px;
  border-radius: 10px;
  border: 1px solid #dee2e6;
}

.slot-actions {
  position: absolute;
  top: 6px;
  right: 6px;
  opacity: 0;
  transition: opacity 0.2s ease;
  display: flex;
  gap: 4px;
}

.canvas-slot:hover .slot-actions {
  opacity: 1;
}

.slot-action-btn {
  border: none;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: white;
  font-size: 10px;
  transition: all 0.2s ease;
}

.reset-btn {
  background: rgba(40, 167, 69, 0.9);
}

.reset-btn:hover {
  background: #28a745;
  transform: scale(1.1);
}

.delete-btn {
  background: rgba(220, 53, 69, 0.9);
}

.delete-btn:hover {
  background: #dc3545;
  transform: scale(1.1);
}

.edit-tips {
  position: absolute;
  bottom: 6px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(40, 167, 69, 0.9);
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 10px;
  font-weight: 500;
  white-space: nowrap;
}

/* 右侧图片库 */
.photo-panel {
  width: 320px;
  background: white;
  border-left: 1px solid #e9ecef;
  display: flex;
  flex-direction: column;
}

.photo-panel .panel-header {
  padding: 20px;
  border-bottom: 1px solid #e9ecef;
}

.photo-panel .panel-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #212529;
}

.panel-content {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

/* 上传区域 */
.upload-zone {
  border: 2px dashed #dee2e6;
  border-radius: 8px;
  padding: 24px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s ease;
  background: #f8f9fa;
  margin-bottom: 20px;
}

.upload-zone:hover,
.upload-zone.drag-over {
  border-color: #007bff;
  background: rgba(0, 123, 255, 0.05);
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.upload-content svg {
  font-size: 32px;
  color: #6c757d;
}

.upload-content p {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
  color: #495057;
}

.upload-content span {
  font-size: 12px;
  color: #6c757d;
}

/* 图片列表 */
.photo-list {
  margin-bottom: 24px;
}

.photo-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.photo-header span {
  font-size: 14px;
  font-weight: 500;
  color: #495057;
}

.clear-btn {
  padding: 4px 8px;
  background: transparent;
  color: #dc3545;
  border: 1px solid #dc3545;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.clear-btn:hover {
  background: #dc3545;
  color: white;
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.photo-item {
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  overflow: hidden;
  cursor: grab;
  transition: all 0.2s ease;
}

.photo-item:hover {
  border-color: #007bff;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.15);
  transform: translateY(-1px);
}

.photo-item:active {
  cursor: grabbing;
}

.photo-thumbnail {
  position: relative;
  aspect-ratio: 1;
  overflow: hidden;
}

.photo-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.photo-overlay {
  position: absolute;
  top: 6px;
  right: 6px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.photo-item:hover .photo-overlay {
  opacity: 1;
}

/* 边角控制点样式 */
.corner-controls {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.corner-handle {
  position: absolute;
  width: 8px;
  height: 8px;
  background: #007bff;
  border: 1px solid white;
  border-radius: 50%;
  pointer-events: all;
  cursor: pointer;
  opacity: 0.8;
  transition: all 0.2s ease;
}

.corner-handle:hover {
  opacity: 1;
  transform: scale(1.2);
}

.corner-tl {
  top: -4px;
  left: -4px;
  cursor: nw-resize;
}

.corner-tr {
  top: -4px;
  right: -4px;
  cursor: ne-resize;
}

.corner-bl {
  bottom: -4px;
  left: -4px;
  cursor: sw-resize;
}

.corner-br {
  bottom: -4px;
  right: -4px;
  cursor: se-resize;
}

.remove-btn {
  width: 20px;
  height: 20px;
  background: rgba(220, 53, 69, 0.9);
  border: none;
  border-radius: 50%;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 10px;
  transition: all 0.2s ease;
}

.remove-btn:hover {
  background: #dc3545;
  transform: scale(1.1);
}

.photo-info {
  padding: 8px;
}

.photo-name {
  font-size: 12px;
  font-weight: 500;
  color: #495057;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 2px;
}

.photo-size {
  font-size: 10px;
  color: #6c757d;
}

/* 画布设置 */
.canvas-settings {
  border-top: 1px solid #e9ecef;
  padding-top: 20px;
}

.canvas-settings h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #212529;
}

.setting-group {
  margin-bottom: 16px;
}

.setting-group label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #495057;
  margin-bottom: 6px;
}

.size-inputs {
  display: flex;
  align-items: center;
  gap: 8px;
}

.size-inputs input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  font-size: 14px;
}

.size-inputs span {
  color: #6c757d;
  font-weight: 500;
}

.border-inputs {
  display: flex;
  align-items: center;
  gap: 8px;
}

.border-inputs input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  font-size: 14px;
}

.setting-group input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.2s ease;
}

.setting-group input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .template-panel {
    width: 240px;
  }

  .photo-panel {
    width: 280px;
  }

  .template-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .editor-container {
    flex-direction: column;
  }

  .template-panel,
  .photo-panel {
    width: 100%;
    height: 200px;
  }

  .main-canvas {
    order: -1;
    flex: 1;
  }

  .template-grid {
    grid-template-columns: repeat(4, 1fr);
  }

  .photo-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

/* 暗主题支持 */
.dark .editor-container {
  background: #111827;
}

.dark .template-panel,
.dark .photo-panel {
  background: #1f2937;
  border-color: #374151;
}

.dark .panel-header {
  border-color: #374151;
}

.dark .panel-header h2,
.dark .panel-header h3 {
  color: #f9fafb;
}

.dark .template-count {
  color: #9ca3af;
}

.dark .template-item {
  background: #374151;
  border-color: #4b5563;
}

.dark .template-item:hover {
  border-color: #3b82f6;
  background: #4b5563;
}

.dark .template-item.active {
  border-color: #3b82f6;
  background: #1e3a8a;
}

.dark .template-preview {
  background: #4b5563;
  border-color: #6b7280;
}

.dark .template-name {
  color: #f9fafb;
}

.dark .template-count {
  color: #9ca3af;
}

.dark .main-canvas {
  background: #111827;
}

.dark .top-toolbar {
  background: #1f2937;
  border-color: #374151;
}

.dark .canvas {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}

.dark .canvas-slot {
  border-color: #4b5563;
}

.dark .slot-placeholder {
  color: #9ca3af;
}

.dark .upload-zone {
  background: #374151;
  border-color: #4b5563;
}

.dark .upload-zone:hover {
  background: #4b5563;
  border-color: #6b7280;
}

.dark .upload-content p {
  color: #f9fafb;
}

.dark .upload-content span {
  color: #9ca3af;
}

.dark .photo-header {
  color: #f9fafb;
}

.dark .clear-btn {
  background: #374151;
  color: #f9fafb;
  border-color: #4b5563;
}

.dark .clear-btn:hover {
  background: #4b5563;
}

.dark .photo-item {
  background: #374151;
  border-color: #4b5563;
}

.dark .photo-name {
  color: #f9fafb;
}

.dark .photo-size {
  color: #9ca3af;
}

.dark .canvas-settings {
  border-color: #374151;
}

.dark .canvas-settings h4 {
  color: #f9fafb;
}

.dark .setting-group label {
  color: #f9fafb;
}

.dark .size-inputs input,
.dark .border-inputs input {
  background: #374151;
  border-color: #4b5563;
  color: #f9fafb;
}

.dark .size-inputs input:focus,
.dark .border-inputs input:focus {
  border-color: #3b82f6;
}
</style>
